<template>
  <div class="p-2">
    <el-card class="p-2" shadow="never">
      <div class="menu-top">
        <div>
          <el-button type="primary" :loading="buttonLoading" :disabled="form.auditStatus === 2" @click="submitForm"> 保存 </el-button>
          <el-button type="success">复制</el-button>
          <el-button type="warning" @click="handleClose">关闭</el-button>
          <!--约定超过15天后的单据不能作废-->
          <el-button v-if="form.auditStatus === 2" type="danger" :disabled="isVoid < 15" @click="handleVoid">作废 </el-button>
        </div>
        <div>
          <el-form ref="farmSaleFormRef" :model="form" :rules="rules" label-width="80px">
            <el-form-item label="标题" prop="title">
              <el-input v-model="form.title" :disabled="form.auditStatus === 2" placeholder="请输入标题" />
            </el-form-item>
          </el-form>
        </div>
      </div>
      <div style="border-bottom: 1px solid #eee; margin: 20px -15px" />
      <div>
        <el-form ref="farmSaleFormRef" :model="form" :rules="rules" label-width="120px">
          <el-row :gutter="20">
            <el-col :span="6">
              <el-form-item label="销售员" prop="workerId">
                <el-select v-model="form.workerId" :disabled="form.auditStatus === 2" placeholder="请选择销售员">
                  <el-option v-for="item in userList" :key="item.userId" :label="item.nickName" :value="item.userId" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="买家" prop="buyer">
                <el-input v-model="form.buyer" placeholder="请输入购买方" />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="联系电话" prop="buyerTel">
                <el-input v-model="form.buyerTel" placeholder="请输入联系电话" />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="配送地址" prop="buyerAddr">
                <el-input v-model="form.buyerAddr" placeholder="请输入配送地址" />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="是否付款" prop="isPayment">
                <el-select v-model="form.isPayment" placeholder="请选择是否付款">
                  <el-option v-for="dict in payment_status" :key="dict.value" :label="dict.label" :value="dict.value"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="已付款金额" prop="paidMoney">
                <el-input v-model="form.paidMoney" placeholder="请输入已付款金额" />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="是否提成" prop="isCommission">
                <el-radio-group v-model="form.isCommission">
                  <el-radio v-for="dict in order_is" :key="dict.value" :label="dict.value">{{ dict.label }}</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="提成比例" prop="commissionRate">
                <el-input v-model="form.commissionRate" placeholder="请输入提成比例" @input="computedCommission">
                  <template #append>%</template>
                </el-input>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="佣金" prop="commissionMoney">
                <el-input v-model="form.commissionMoney" placeholder="请输入佣金" />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="销售日期" prop="saleTime">
                <el-date-picker v-model="form.saleTime" clearable type="date" value-format="YYYY-MM-DD HH:mm:ss" placeholder="请选择销售日期">
                </el-date-picker>
              </el-form-item>
            </el-col>
            <el-col v-if="form.auditStatus > 1" :span="6">
              <el-form-item label="制单人" prop="createBy">
                <el-select v-model="form.createBy" disabled>
                  <el-option v-for="item in userList" :key="item.userId" :label="item.nickName" :value="item.userId" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col v-if="form.auditStatus > 1" :span="6">
              <el-form-item label="制单时间" prop="createTime">
                <el-input v-model="form.createTime" disabled />
              </el-form-item>
            </el-col>
            <el-col v-if="form.auditStatus > 1" :span="6">
              <el-form-item label="审核时间" prop="auditTime">
                <el-input v-model="form.auditTime" disabled />
              </el-form-item>
            </el-col>
            <el-col v-if="form.auditStatus > 1" :span="6">
              <el-form-item label="审核人" prop="auditBy">
                <el-select v-model="form.auditBy" disabled>
                  <el-option v-for="item in userList" :key="item.userId" :label="item.nickName" :value="item.userId" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col v-if="form.auditStatus > 1" :span="6">
              <el-form-item label="单据状态" prop="auditStatus">
                <el-select v-model="form.auditStatus" disabled>
                  <el-option v-for="dict in order_status" :key="dict.value" :value="dict.value" :label="dict.label" />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </div>
      <el-form-item>
        <ProductsSearch v-if="form.auditStatus != 2" :search-type="2" data-text="新增一行" :params="{ isCustomer: true }" @ok="addLine" />
      </el-form-item>
      <div>
        <el-table
          border
          :data="form.contentInfo || []"
          :row-class-name="rowClassName"
          :header-cell-style="{ background: 'F1F5FC' }"
          :summary-method="getSummaries"
          show-summary
        >
          <el-table-column prop="xh" width="88" label="序号" align="center">
            <template #default="scope">
              <div class="xh-show">{{ scope.row.xh }}</div>
              <div class="operation_show">
                <el-button :disabled="form.auditStatus === 2" class="button-del" circle size="small" @click="deleteLine(scope.row, scope.$index)">
                  <el-icon>
                    <Minus />
                  </el-icon>
                </el-button>
              </div>
            </template>
          </el-table-column>
          <el-table-column v-slot="scope" label="产品类别">
            <el-tree-select
              v-model="scope.row.cateId"
              :data="assetCategoryOptions"
              :props="{ value: 'id', label: 'name', children: 'children' }"
              value-key="id"
              filterable
              :render-after-expand="false"
            />
          </el-table-column>
          <el-table-column v-slot="scope" label="选择产品">
            <el-select v-model="scope.row.productId">
              <el-option v-for="item in productsList" :key="item.id" :value="item.id" :label="item.name" />
            </el-select>
          </el-table-column>
          <el-table-column v-slot="scope" label="基本单位">
            <el-select v-model="scope.row.unitId">
              <el-option v-for="item in erpUnitList" :key="item.id" :value="item.id" :label="item.name" />
            </el-select>
          </el-table-column>
          <el-table-column label="数量" prop="amount">
            <template #default="scope">
              <el-input v-model="scope.row.amount" :disabled="form.auditStatus === 2" placeholder="请输入" @input="computerCostMoney(scope.row)" />
            </template>
          </el-table-column>
          <el-table-column v-slot="scope" label="单价">
            <el-input v-model="scope.row.price" :disabled="form.auditStatus === 2" placeholder="请输入" />
          </el-table-column>
          <el-table-column prop="money" label="金额">
            <template #default="scope">
              <el-input v-model="scope.row.money" :disabled="form.auditStatus === 2" />
            </template>
          </el-table-column>
        </el-table>
      </div>

      <div style="position: absolute; margin-top: 10px; right: 30px">
        <el-form ref="farmSaleFormRef" :model="form" :rules="rules" inline label-width="100">
          <el-form-item label="合计数量" prop="totalNum">
            <el-input v-model="form.totalNum" placeholder="请输入合计数量" />
          </el-form-item>
          <el-form-item label="合计金额" prop="totalMoney">
            <el-input v-model="form.totalMoney" placeholder="请输入合计金额" />
          </el-form-item>
        </el-form>
      </div>
      <div style="margin-top: 50px">
        <div style="margin-bottom: 10px; display: flex">
          <el-button type="primary" size="small">上传附件</el-button>
          <span style="margin-left: 10px; font-size: 12px; margin-top: 2px">(建议上传附件大小在5M以内)</span>
        </div>
        <el-form ref="farmSaleFormRef" :model="form" :rules="rules" label-width="80px">
          <el-row :gutter="20">
            <el-col :span="18">
              <el-form-item label="说明备注" prop="remark">
                <el-input v-model="form.remark" :disabled="form.auditStatus === 2" type="textarea" rows="3" placeholder="请输入说明备注" />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="登记人" prop="createBy">
                <el-select v-model="form.createBy" disabled>
                  <el-option v-for="item in userList" :key="item.userId" :label="item.nickName" :value="item.userId" />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </div>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { listUser } from '@/api/system/user';
import { listAssetCategory } from '@/api/erp/assetCategory';
import ProductsSearch from '@/views/erp/products/search.vue';
import { listProducts } from '@/api/erp/products';
import { ProductsVO } from '@/api/erp/products/types';
import { listErpUnit } from '@/api/erp/erpUnit';
import { ErpUnitVO } from '@/api/erp/erpUnit/types';
import dayjs from 'dayjs';
import { FarmSaleForm, FarmSaleQuery } from '@/api/erp/farmSale/types';
import { FarmSaleInfoVO } from '@/api/erp/farmSaleInfo/types';
import { addFarmSale, auditFarmSaleApi, defaultTitle, updateFarmSale } from '@/api/erp/farmSale';
import { delFarmSaleInfo } from '@/api/erp/farmSaleInfo';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const emit = defineEmits(['closeAdd', 'getList']);
const assetCategoryOptions = ref<AssetCategoryOption[]>([]);
type AssetCategoryOption = {
  id: number;
  name: string;
  children?: AssetCategoryOption[];
};
const { order_is, payment_status, order_status } = toRefs<any>(proxy?.useDict('order_is', 'payment_status', 'order_status'));
const erpUnitList = ref<ErpUnitVO[]>([]);
const props = defineProps({
  rowData: {
    type: Object,
    default: null
  }
});
const auditForm = reactive<any>({
  id: props.rowData.id,
  auditTime: undefined,
  auditStatus: '4',
  auditRemark: undefined
});
const farmSaleFormRef = ref<ElFormInstance>();
const buttonLoading = ref(false);
const initFormData: FarmSaleForm = {
  contentInfo: [],
  id: undefined,
  title: undefined,
  buyer: undefined,
  buyerTel: undefined,
  buyerAddr: undefined,
  workerId: undefined,
  totalNum: undefined,
  totalMoney: undefined,
  isPayment: undefined,
  paidMoney: undefined,
  isCommission: undefined,
  commissionRate: undefined,
  commissionMoney: undefined,
  saleTime: undefined,
  remark: undefined
};
const data = reactive<PageData<FarmSaleForm, FarmSaleQuery>>({
  form: { ...initFormData },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    title: undefined,
    auditStatus: undefined,
    params: {}
  },
  rules: {
    id: [{ required: true, message: '不能为空', trigger: 'blur' }],
    title: [{ required: true, message: '不能为空', trigger: 'blur' }],
    totalNum: [{ required: true, message: '合计数量不能为空', trigger: 'blur' }],
    totalMoney: [{ required: true, message: '合计金额不能为空', trigger: 'blur' }],
    isPayment: [{ required: true, message: '是否付款不能为空', trigger: 'change' }],
    saleTime: [{ required: true, message: '销售日期不能为空', trigger: 'blur' }],
    commissionRate: [{ required: true, message: '提成比例不能为空', trigger: 'blur' }]
  }
});

const { queryParams, form, rules } = toRefs(data);
const isVoid = ref<number>();
watch(
  () => props.rowData,
  () => {
    console.log(props.rowData);
    form.value = props.rowData;
    if (props.rowData.contentInfo.length === 0) {
      form.value.contentInfo = [{}];
    }
  }
);

/*作废操作*/
/*设置过期时间*/
let a = dayjs(props.rowData.createTime).unix();
let b = dayjs().unix();
isVoid.value = (b - a) / (60 * 60 * 24);

//TODO 超过一定时间后不能将订单作废
const handleVoid = async () => {
  console.log(props.rowData.id);
  await proxy?.$modal.confirm('是否确认将鸡场投喂编号为"' + props.rowData.id + '"的数据作废？').finally();
  let res = await auditFarmSaleApi(auditForm);
  if (res.code === 200) {
    proxy?.$modal.msgSuccess('已作废,库存已变更');
    handleClose();
    emit('getList');
  }
};
/*获取默认标题*/
const getTitle = async () => {
  let res = await defaultTitle();
  form.value.title = res.data;
};
/*获取用户列表*/
const userList = ref([]);
const userData = async () => {
  const { rows } = await listUser(null);
  userList.value = rows;
};

/*获取商品列表*/
const productsList = ref([]);
const getProductsList = async () => {
  const res = await listProducts(null);
  productsList.value = res.rows;
};
/*获取商品基本单位*/
const getUnitList = async () => {
  const res = await listErpUnit(queryParams.value);
  erpUnitList.value = res.rows;
};
/*获取资产类别*/
const getTreeSelect = async () => {
  const res = await listAssetCategory();
  assetCategoryOptions.value = [];
  const data: AssetCategoryOption = { id: 0, name: '顶级节点', children: [] };
  data.children = proxy?.handleTree<AssetCategoryOption>(res.data, 'id', 'parentId');
  assetCategoryOptions.value.push(data);
};

const rowClassName = ({ row, rowIndex }: { row: any; rowIndex: number }) => {
  row.index = rowIndex; // 把每一行的索引放进row
  row.xh = rowIndex + 1;
};

/** 删除行数*/
const deleteLine = async (row: any, $index: any) => {
  if (row.id) {
    //如果有ID说明存在数据表里，需请求后台删除
    const { code } = await delFarmSaleInfo(row.id);
    if (code === 200) {
      proxy?.$modal.msgSuccess('删除成功');
      form.value.contentInfo.splice($index, 1);
    }
  } else {
    //未存入的则直接删除
    form.value.contentInfo.splice($index, 1);
  }
};
/*计算佣金*/
const computedCommission = () => {
  let money = (form.value.commissionRate * form.value.paidMoney) / 100;
  form.value.commissionMoney = Number(money.toFixed(2));
};
/*打开商品列表-选择*/
const addLine = (vo: ProductsVO[]) => {
  vo.forEach((v) => {
    console.log(v);
    form.value.contentInfo.push({
      productId: v.id,
      price: v.price,
      cateId: v.cateId,
      unitId: v.unitId
    });
  });
};

/** 自定义求和*/
const getSummaries = (param) => {
  const { columns, data } = param;
  const sums: (string | VNode)[] = [];
  columns.forEach((column, index) => {
    if (index === 0) {
      sums[index] = h('div', { style: { textDecoration: 'underline' } }, ['合计']);
      return;
      // 可以根据索引判断是否合计
    } else if (index === 4 || index === 6) {
      const values = data.map((item) => Number(item[column.property]));
      if (!values.every((value) => Number.isNaN(value))) {
        sums[index] = `${values.reduce((prev, curr) => {
          const value = Number(curr);
          if (!Number.isNaN(value)) {
            let total = prev + curr;
            if (index === 4) {
              form.value.totalNum = total.toFixed(2);
            } else if (index === 6) {
              form.value.totalMoney = total.toFixed(2);
            }
            return total;
          } else {
            return prev;
          }
        }, 0)}`;
        return sums[index];
      } else {
        sums[index] = 'N/A';
      }
    }
  });
  return sums;
};

/*表格计算*/
const computerCostMoney = (vo: FarmSaleInfoVO) => {
  vo.money = (vo.amount! * vo.price!).toFixed(2);
};
/*关闭新增界面*/
const handleClose = () => {
  emit('closeAdd', 1);
};
/** 表单重置 */
const reset = () => {
  form.value = { ...initFormData };
  farmSaleFormRef.value?.resetFields();
};
/** 提交按钮 */
const submitForm = () => {
  farmSaleFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      if (form.value.id) {
        await updateFarmSale(form.value).finally(() => (buttonLoading.value = false));
        proxy?.$modal.msgSuccess('修改成功');
      } else {
        await addFarmSale(form.value).finally(() => (buttonLoading.value = false));
        proxy?.$modal.msgSuccess('增加成功');
      }
      handleClose();
      emit('getList');
    }
  });
};
onMounted(() => {
  if (!props.rowData.id) {
    getTitle();
  }
  userData();
  getTreeSelect();
  getProductsList();
  getUnitList();
});
</script>

<style scoped lang="scss">
.menu-top {
  display: flex;
  justify-content: space-between;

  .el-form-item {
    margin-bottom: 0;
  }
}

.button-add {
  color: #3a8ee6;
  font-size: 14px;
}

.button-del {
  color: red;
  font-size: 14px;
}

.xh-show {
  display: block;
}

.operation_show {
  display: none;
}

.el-table__body tr:hover > td .operation_show {
  display: block;
}

.el-table__body tr:hover > td .xh-show {
  display: none;
}
</style>
